const { BASE_API } = require('../config/index')

/**
 * HTTP 请求封装
 * @param {string} method - 请求方法
 * @param {string} url - 请求路径
 * @param {Object} options - 请求配置
 */
function request(method, url, { data, headers } = {}) {
  return new Promise((resolve, reject) => {
    // 自动携带 Token
    const token = wx.getStorageSync('token')
    const requestHeaders = Object.assign({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }, headers || {})
    
    // 如果有 Token，添加到请求头
    if (token) {
      requestHeaders['Authorization'] = `Bearer ${token}`
    }
    
    wx.request({
      method,
      url: url.startsWith('http') ? url : `${BASE_API}${url}`,
      data,
      header: requestHeaders,
      success(res) {
        const ct = res.header && (res.header['content-type'] || res.header['Content-Type'] || '')
        if (ct && ct.includes('octet-stream')) return resolve(res.data)

        const payload = res.data
        if (payload && typeof payload === 'object' && 'code' in payload && 'data' in payload) {
          if (payload.code === 0) return resolve(payload.data)
          
          // 处理 401 未授权
          if (payload.code === 401) {
            wx.removeStorageSync('token')
            wx.removeStorageSync('userId')
            wx.removeStorageSync('username')
            
            // 提示用户重新登录
            wx.showToast({
              title: '请先登录',
              icon: 'none',
              duration: 2000
            })
            
            // 跳转到登录页（需要创建登录页面）
            setTimeout(() => {
              wx.navigateTo({ url: '/pages/login/login' })
            }, 2000)
          }
          
          const err = new Error(payload.message || '业务失败')
          err.code = payload.code
          return reject(err)
        }
        return resolve(payload) // 兜底
      },
      fail(e) { reject(new Error(e.errMsg || '网络不可用或服务器无响应')) }
    })
  })
}

module.exports = {
  get: (url, opts) => request('GET', url, opts),
  post: (url, opts) => request('POST', url, opts),
  request
}
